const { Controller } = require("egg");
const { v4: uuidv4 } = require("uuid");
const { loginRule } = require("../validate/account");
const { encryptData } = require("../utils/crypto");

class UserController extends Controller {
	async login() {
		const { ctx, service } = this;
		const { account, password } = ctx.request.body;

		ctx.validate(loginRule);

		const encrypt = encryptData(password);
		const user = await service.user.find({ account, password: encrypt });
		const code = user ? 200 : 400;
		const msg = user ? "登录成功" : "账号或密码有误";
		ctx.body = {
			data: user,
			code,
			msg
		};
	}
	async addUser() {
		const { ctx, service } = this;
		const { account, password } = ctx.request.body;

		ctx.validate(loginRule);

		const encrypt = encryptData(password);

		// 生成UUID
		const userId = uuidv4();
		const result = await service.user.insert({ id: userId, account, password: encrypt });
		ctx.body = {
			code: 200,
			result
		};
	}
}
module.exports = UserController;
